package meiyunting.shiwuzhaoling.controller;

import lombok.extern.slf4j.Slf4j;
import meiyunting.shiwuzhaoling.service.CircuitBreakerDemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 熔断器控制器
 * 提供API接口，用于测试和展示熔断器功能
 */
@Slf4j
@RestController
@RequestMapping("/api/circuit-breaker")
public class CircuitBreakerController {

    @Autowired
    private CircuitBreakerDemoService circuitBreakerDemoService;
    
    @Value("${server.port}")
    private String serverPort;
    
    /**
     * 使用熔断器调用服务
     * @return 调用结果
     */
    @GetMapping("/call")
    public Map<String, Object> callWithCircuitBreaker() {
        log.info("从端口 {} 发起带熔断器的服务调用", serverPort);
        
        Map<String, Object> result = circuitBreakerDemoService.callInstanceInfoWithCircuitBreaker();
        
        // 添加当前端口信息
        result.put("sourcePort", serverPort);
        
        return result;
    }
    
    /**
     * 获取用户的失物信息（带熔断器）
     * @param userId 用户ID
     * @return 失物列表
     */
    @GetMapping("/lost-items/{userId}")
    public Map<String, Object> getUserLostItems(@PathVariable Long userId) {
        log.info("从端口 {} 发起带熔断器的获取用户失物信息调用，用户ID: {}", serverPort, userId);
        
        List<Map<String, Object>> items = circuitBreakerDemoService.getUserLostItemsWithCircuitBreaker(userId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("sourcePort", serverPort);
        result.put("userId", userId);
        result.put("items", items);
        
        return result;
    }
    
    /**
     * 切换服务可用状态（用于测试）
     * @return 当前服务状态
     */
    @GetMapping("/toggle")
    public Map<String, Object> toggleServiceAvailability() {
        boolean available = circuitBreakerDemoService.toggleServiceAvailability();
        
        Map<String, Object> result = new HashMap<>();
        result.put("serviceAvailable", available);
        result.put("message", available ? "服务已恢复可用" : "服务已设置为不可用状态");
        
        return result;
    }
    
    /**
     * 获取服务调用统计信息
     * @return 统计信息
     */
    @GetMapping("/stats")
    public Map<String, Object> getStatistics() {
        return circuitBreakerDemoService.getStatistics();
    }
    
    /**
     * 重置统计信息
     * @return 重置结果
     */
    @GetMapping("/reset")
    public Map<String, Object> resetStatistics() {
        circuitBreakerDemoService.resetStatistics();
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "统计信息已重置");
        
        return result;
    }
} 